package com.xneure.database;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import com.xneure.database.annotation.DynamicSource;

@Aspect
@Component("daoAspect")
public class DataSourceAspect implements Ordered{
	@Around("this(com.xneure.database.dao.DataBaseDao)")
	public Object traceMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
		String defDb = null;
		MethodSignature t = (MethodSignature)proceedingJoinPoint.getSignature();
		try{
			DynamicDataSource.setCurrMethod(t.getMethod());
			DynamicSource annotation = t.getMethod().getAnnotation(DynamicSource.class);
			if(null != annotation && annotation.value().length() > 0){
				defDb = DynamicDataSource.getCurrDataSource();
				DynamicDataSource.setCurrDataSource(annotation.value());
			}
			return proceedingJoinPoint.proceed();
		}finally{
			if(defDb != null){
				DynamicDataSource.setCurrDataSource(defDb);
			}
		}
	}

	// 拦截所有的service操作
	@Override
	public int getOrder(){
		return 1;
	}
}
